package com.walk.zworld.view.location.amap;

import static com.amap.api.services.core.ServiceSettings.updatePrivacyAgree;
import static com.amap.api.services.core.ServiceSettings.updatePrivacyShow;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.base.lib.base.utils.ToastUtil;
import com.base.lib.common.utils.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.walk.zworld.R;
import com.walk.zworld.api.bean.AddressCommitBean;
import com.walk.zworld.api.bean.AddressInfoBean;
import com.walk.zworld.api.http.BaseHttpCallBack;
import com.walk.zworld.api.http.CommonAppConfig;
import com.walk.zworld.api.http.HttpClient;
import com.walk.zworld.api.http.ParseArrayHttpCallBack;
import com.walk.zworld.api.utils.ListUtil;
import com.walk.zworld.api.utils.MapBuilder;
import com.walk.zworld.api.utils.RequestFactory;
import com.walk.zworld.utils.observer.DialogObserver;
import com.walk.zworld.view.location.LocationSelectorAddressAdapter;
import com.walk.zworld.view.location.tenbean.LocationSelectorResultModel;
import com.base.lib.common.utils.SoftInputUtil;
import com.walk.zworld.view.location.tenbean.TencentPoiModel;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.reactivex.Observable;

public class LocationAmapSelectorActivity extends Activity implements
        GeocodeSearch.OnGeocodeSearchListener,
//        AMap.OnMarkerClickListener,
//        AMap.InfoWindowAdapter,
        PoiSearch.OnPoiSearchListener {

    private MapView mapView;//地图页面
    private AMap aMap = null;//地图控制器
    public String city;//城市
    public String cityCode;//城市码
    private FloatingActionButton getLocal;
    private String Title;
    private String Snippet;
    private String Localaddress;
    private String Titlezb;
    private String Snippetzb;
    private double latitude;
    private double longitude;
    private EditText et_keyword;//文本
    public AMapLocationClient mLocationClient = null;//声明AMapLocationClient类对象
    public AMapLocationClientOption mLocationOption = null;//声明AMapLocationClientOption对象
    private GeocodeSearch geocodeSearch;//地理编码搜索
    private static final int PARSE_SUCCESS_CODE = 1000;//解析成功标识码
    private static final int REQUEST_PERMISSIONS = 9527;//请求权限码
    private String POI_SEARCH_TYPE = "汽车服务|汽车销售|" +
            "//汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|" +
            "//住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|" +
            "//金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";

    private ProgressDialog progDialog = null;// 搜索时进度条
    private String mKeyWords = "";// 要输入的poi搜索关键字
    private int currentPage = 1;
    private PoiResult poiResult; // poi返回的结果
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索
    private Marker mPoiMarker;
    public static final int REQUEST_CODE = 100;
    public static final int RESULT_CODE_INPUTTIPS = 101;
    public static final int RESULT_CODE_KEYWORDS = 102;
    public static final int RESULT_CODE_ZHOUBIAN = 103;
    private SharedPreferences sp;
    private ImageView ivCollapse;
    private ConstraintLayout clMapArea;
    private RecyclerView rvAddressList;
    private LocationSelectorAddressAdapter mAdapter;
    private long mLastCameraChangeTimestamp = 0L;
    private LatLng mCurrentLatLng = new LatLng(0, 0);
    private float lastslideOffset = -1f;
    private AddressInfoBean mAddressInfoBean;
    private String mSelectTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        updatePrivacyShow(this,true,true);
        updatePrivacyAgree(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.location_activity_amap_selector);
        sp = getSharedPreferences("Personal", MODE_PRIVATE);
        mapView = findViewById(R.id.map_view);//定义了一个地图view1
        mapView.onCreate(savedInstanceState);//此方法须覆写，虚拟机需要在很多情况下保存地图绘制的当前状态。

        et_keyword = findViewById(R.id.et_keyword);
        getLocal = findViewById(R.id.GetLocal);
        ivCollapse = findViewById(R.id.iv_collapse);
        clMapArea = findViewById(R.id.cl_map_area);
        rvAddressList = findViewById(R.id.rv_address_list);
        rvAddressList.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new LocationSelectorAddressAdapter();
        rvAddressList.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                TencentPoiModel data = mAdapter.getItem(position);
                if (data.getAddress().equals(mSelectAddress)) {
                    return;
                }
                mLastCameraChangeTimestamp = System.currentTimeMillis();
                double lng = data.getLatLng().longitude;
                double lat = data.getLatLng().latitude;
                mSelectAddress = data.getAddress();
                mSelectTitle = data.getTitle();
                mSelectLng = lng+"";
                mSelectLat = lat+"";
                LatLng latLng = new LatLng(lat, lng);
                CameraPosition cameraPosition = new CameraPosition(latLng, 15F, 0F, 0F);
//                playIvCenterPosAnim();
                CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 18f);
                aMap.moveCamera(cameraUpdate);
                mAdapter.setActivePosition(position);
            }
        });
        et_keyword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                if (mAdapter.getActivePosition() != -1) {
                    mAdapter.setActivePosition(-1);
                }
//                mViewModel.requestData(mTencentSearch, true)
            }
        });
        mBottomSheetBehavior = BottomSheetBehavior.from(findViewById(R.id.view_bottom_sheet));
        mBottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_DRAGGING) {
                    SoftInputUtil.INSTANCE.hideSoftInput(LocationAmapSelectorActivity.this, bottomSheet);
                }
                if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                    SoftInputUtil.INSTANCE.hideSoftInput(LocationAmapSelectorActivity.this, bottomSheet);
                }
            }
            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                Log.d("TAG", "onSlide: slideOffset=" + slideOffset);
                mBottomSheetHeight = bottomSheet.getHeight();
                processLayoutParams(slideOffset);
            }
        });
        if (aMap == null) {
            aMap = mapView.getMap();//初始化地图控制器对象
        }
        initLocation();
        setStatusBar();
        checkingAndroidVersion();

        getLocal.setOnClickListener(v -> {
            GetOnceLocation();
            landian();
        });
        try {
            geocodeSearch = new GeocodeSearch(this);
        } catch (AMapException e) {
            e.printStackTrace();
        }
        geocodeSearch.setOnGeocodeSearchListener(this);
        mKeyWords = "";
        processLayoutParams(0F);

        getDefaultAddress(new ParseArrayHttpCallBack<AddressInfoBean>() {
            @Override
            public void onSuccess(int code, String msg, List<AddressInfoBean> info) {
                if(isSuccess(code)&& ListUtil.haveData(info)){
                    mAddressInfoBean=info.get(0);
                    mSelectAddress = mAddressInfoBean.getAddress();
                    mSelectTitle = mAddressInfoBean.getName();
                    mSelectLng = mAddressInfoBean.getCity();
                    mSelectLat = mAddressInfoBean.getProvince();
                    LatLng latLng = new LatLng(Double.parseDouble(mSelectLat), Double.parseDouble(mSelectLng));
                    CameraPosition cameraPosition = new CameraPosition(latLng, 15F, 0F, 0F);
                    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 18f);
                    aMap.moveCamera(cameraUpdate);
                } else {
                    findViewById(R.id.choose_address_btn).setVisibility(View.VISIBLE);
                    //启动定位
                    landian();
                    GetOnceLocation();
                }
            }
        });
    }

//    /**
//     * 设置页面监听
//     */
//    private void setUpMap() {
//        aMap.setOnMarkerClickListener(this);// 添加点击marker监听事件
//        aMap.setInfoWindowAdapter(this);// 添加显示infowindow监听事件
//        aMap.getUiSettings().setRotateGesturesEnabled(false);
//    }

    private void processLayoutParams(Float slideOffset) {
        if (lastslideOffset == slideOffset || (slideOffset!=1&& slideOffset!=0 && Math.abs(slideOffset-lastslideOffset)<0.1)) {
            return;
        }
        lastslideOffset = slideOffset;
        LinearInterpolator interpolator = new LinearInterpolator();
        int marginBottom = 8;
        int bottomHeight = mBottomSheetHeight - mBottomSheetBehavior.getPeekHeight();
        // 计算插值后的偏移量
        float offset = interpolator.getInterpolation(slideOffset) * bottomHeight;
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams)clMapArea.getLayoutParams();
        params.bottomMargin = (int) (offset + marginBottom);
        clMapArea.requestLayout();

        ViewGroup.LayoutParams ivCollapseParams = ivCollapse.getLayoutParams();
        ivCollapseParams.height = (int)(mIvCollapseHeight * slideOffset);
        ivCollapse.requestLayout();
    }

    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null)
            progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(false);
        progDialog.setMessage("正在搜索:\n" + mKeyWords);
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String keywords) {
        showProgressDialog();// 显示进度框
        currentPage = 1;
        // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query = new PoiSearch.Query(keywords, POI_SEARCH_TYPE, "");
        // 设置每页最多返回多少条poiitem
        query.setPageSize(50);
        // 设置查第一页
        query.setPageNum(currentPage);

        if (mCurrentLatLng.latitude != 0) {
            LatLonPoint latLonPoint = new LatLonPoint(mCurrentLatLng.latitude, mCurrentLatLng.longitude);
            query.setLocation(latLonPoint);
        }
        try {
            poiSearch = new PoiSearch(this, query);
        } catch (AMapException e) {
            e.printStackTrace();
        }
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

//    @Override
//    public boolean onMarkerClick(Marker marker) {
//        marker.showInfoWindow();
//        return false;
//    }

//    @Override
//    public View getInfoContents(Marker marker) {
//        return null;
//    }
//
//    @Override
//    public View getInfoWindow(final Marker marker) {
//        View view = getLayoutInflater().inflate(R.layout.poikeywordsearch_uri,
//                null);
//        TextView title = (TextView) view.findViewById(R.id.title);
//        title.setText(marker.getTitle());
//
//        TextView snippet = (TextView) view.findViewById(R.id.snippet);
//        snippet.setText("地址："+marker.getSnippet());
//        return view;
//    }

    /**
     * poi没有搜索到数据，返回一些推荐城市的信息
     */
    private void showSuggestCity(List<SuggestionCity> cities) {
        String infomation = "搜索不到，推荐城市\n";
        for (int i = 0; i < cities.size(); i++) {
            infomation += "城市名称:" + cities.get(i).getCityName() + "\n";
        }
        ToastUtil.showToast(infomation);

    }

    /**
     * POI信息查询回调方法
     */
    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        dissmissProgressDialog();// 隐藏对话框
        if (rCode == 1000) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                    if (poiItems != null && poiItems.size() > 0) {
                        aMap.clear();// 清理之前的图标
                        ArrayList<TencentPoiModel> tencentPoiModels = new ArrayList<>();
                        for (PoiItem poiItem : poiItems) {
                            com.tencent.tencentmap.mapsdk.maps.model.LatLng latLng = new com.tencent.tencentmap.mapsdk.maps.model.LatLng(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude());
                            String direction = poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName() + poiItem.getDirection();
                            TencentPoiModel tencentPoiModel = new TencentPoiModel(direction,poiItem.getTitle(),poiItem.getSnippet(),latLng);
                            tencentPoiModels.add(tencentPoiModel);
                        }
                        mSelectAddress = "";
                        mAdapter.setActivePosition(-1);
                        mAdapter.setList(tencentPoiModels);
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
                        showSuggestCity(suggestionCities);
                    } else {
                        ToastUtil.showToast("无搜索结果");
                    }
                }
            } else {
                ToastUtil.showToast("无搜索结果");
            }
        } else {
            ToastUtil.showToast(rCode);
        }

    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    /**
     * 输入提示activity选择结果后的处理逻辑
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 用marker展示输入提示list选中数据
     *
     * @param tip
     */
    private void addTipMarker(Tip tip) {
        if (tip == null) {
            return;
        }
        mPoiMarker = aMap.addMarker(new MarkerOptions());
        LatLonPoint point = tip.getPoint();
        if (point != null) {
            LatLng markerPosition = new LatLng(point.getLatitude(), point.getLongitude());
            mPoiMarker.setPosition(markerPosition);
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerPosition, 17));
        }
        mPoiMarker.setTitle(tip.getName());
        mPoiMarker.setSnippet(tip.getAddress());
        Title = tip.getName();
        Snippet = tip.getAddress();
    }

    /**
     * 用marker展示输入提示list选中数据
     *
     * @param
     */
    private void addMarker(LatLng latLng) {
        mPoiMarker = aMap.addMarker(new MarkerOptions());
        if (latLng != null) {
            mPoiMarker.setPosition(latLng);
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
        }
        mPoiMarker.setTitle("地点："+Titlezb);
        mPoiMarker.setSnippet("地址："+Snippetzb);
    }

    public void landian(){
        //定义一个UiSettings对象
        UiSettings mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        // 自定义定位蓝点图标（此处替换成自己的icon图标就可以了）
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.ic_locate_map_current_pos));
        myLocationStyle.radiusFillColor(0);
        myLocationStyle.strokeColor(0);
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(false);//设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
        mUiSettings.setScaleControlsEnabled(true);
        //隐藏缩放按钮
        mUiSettings.setZoomControlsEnabled(true);
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {}
            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                long currentTimestamp = System.currentTimeMillis();
                if (currentTimestamp - mLastCameraChangeTimestamp < 1000) {
                    // 简单的做一个1秒的流控
                    return;
                }
                mLastCameraChangeTimestamp = currentTimestamp;
                double cameraLat = cameraPosition.target.latitude;
                double cameraLng = cameraPosition.target.longitude;
                if (mCurrentLatLng.latitude == cameraLat && mCurrentLatLng.longitude == cameraLng) {
                    return;
                }
                mSelectLng = cameraLng+"";
                mSelectLat = cameraLat+"";
                mCurrentLatLng = new LatLng(cameraLat, cameraLng);
                if (TextUtils.isEmpty(mSelectAddress) || mAdapter.getActivePosition() == -1) {
                    doSearchQuery("");
                }else {
                    mSelectAddress = mAdapter.getItem(mAdapter.getActivePosition()).getAddress()+"附近";
                }
            }
        });
    }
    /**
     * 初始化定位
     */
    private void initLocation() {
        //初始化定位
        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置定位回调监听
        mLocationClient.setLocationListener(mAMapLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
//        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置定位请求超时时间，单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制，高精度定位会产生缓存。
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //设置是否允许模拟位置,默认为true，允许模拟位置
        mLocationOption.setMockEnable(true);
    }

    /**
     * 停止定位
     */
    public void deactivate() {
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }
    /**
     * 检查Android版本
     */
    private void checkingAndroidVersion() {
        mLocationClient.startLocation();
    }
    public void GetOnceLocation(){
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }


    private void updateMapLocation(LatLng latLng){
        CameraPosition cameraPosition = new CameraPosition(latLng,16,0,0);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.animateCamera(cameraUpdate);
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
        aMap.addMarker(new MarkerOptions().position(latLng).snippet("经度："+convertToLatLonPoint(latLng).getLongitude()+"\n\n纬度："+convertToLatLonPoint(latLng).getLatitude()));
    }


    /**
     * 坐标转地址
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int rCode) {
//解析result获取地址描述信息
        if(rCode == PARSE_SUCCESS_CODE){
            RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
            //显示解析后的地址
            GeocodeQuery query = new GeocodeQuery(regeocodeAddress.getFormatAddress(),"city");
            geocodeSearch.getFromLocationNameAsyn(query);
        }else {
            showMsg("获取地址失败");
        }
    }

    /**
     * 地址转坐标
     * @param geocodeResult
     * @param rCode
     */
    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int rCode) {
    }

    /**
     * 接收异步返回的定位结果
     *
     * @param aMapLocation
     */
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    //地址
                    Localaddress = aMapLocation.getAddress();
                    Log.d("MainActivity","地址信息："+Localaddress);
                    Log.d("MainActivity","GPS状态："+aMapLocation.getGpsAccuracyStatus());
                    //赋值
                    city = aMapLocation.getCity();
                    cityCode = aMapLocation.getCityCode();
                    latitude = (double)Math.round(aMapLocation.getLatitude()*1000)/1000;
                    longitude = (double)Math.round(aMapLocation.getLongitude()*1000)/1000;
                    LatLng latLng = new LatLng(latitude,longitude);
                    aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
                    sp.edit().putString("city",city).apply();
                    sp.edit().putString("Localaddress",Localaddress).apply();
                    sp.edit().putString("latitude",String.valueOf(latitude)).apply();
                    sp.edit().putString("longitude",String.valueOf(longitude)).apply();
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    };

    /**
     * 通过经纬度获取地址
     * @param latLng
     */
    private void latlonToAddress(LatLng latLng) {
        //位置点  通过经纬度进行构建
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        //逆编码查询  第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 5, GeocodeSearch.AMAP);
        //异步获取地址信息
        geocodeSearch.getFromLocationAsyn(query);
    }

    //是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected boolean useThemestatusBarColor = false;
    //是否使用状态栏文字和图标为暗色，如果状态栏采用了白色系，则需要使状态栏和图标为暗色，android6.0以上可以设置
    protected boolean useStatusBarColor = true;
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));//设置状态栏背景色
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);//透明
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        } else {
            Toast.makeText(this, "低于4.4的android系统版本不存在沉浸式状态栏", Toast.LENGTH_SHORT).show();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && useStatusBarColor) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

//    public void gotoNavi(View view) {
//        startActivity(new Intent(this,SearchActivity.class));
//    }
    /**
     * 把LatLng对象转化为LatLonPoint对象
     */
    public static LatLonPoint convertToLatLonPoint(LatLng latLng) {
        return new LatLonPoint(latLng.latitude, latLng.longitude);
    }

    /**
     * 把LatLonPoint对象转化为LatLon对象
     */
    public static LatLng convertToLatLng(LatLonPoint latLonPoint) {
        return new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
    }

    /**
     * 请求权限结果
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //设置权限请求结果
        if(grantResults!=null && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            //授予权限 执行逻辑
            mLocationClient.startLocation();
            landian();
        }else{
            //未授予权限进行提示
            showMsg("没有权限，无法使用");

        }
    }
    /**
     * Toast提示
     * @param msg 提示内容
     */
    private void showMsg(String msg){
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }


    /**
     * 用于数据回传的位置信息
     */
    private String mSelectAddress = "";
    private String mSelectLng;
    private String mSelectLat;
    /**
     * BottomSheet 相关变量
     */
    private BottomSheetBehavior<LinearLayout> mBottomSheetBehavior;
    private int mIvCollapseHeight = 0;
    private int mBottomSheetHeight = 0;
    public void onClickBack(View v) {
        onBackPressed();
    }
    public void onClickDone(View v) {
        if (TextUtils.isEmpty(mSelectAddress)) {
            ToastUtil.showToast("请在下方列表中选择具体地点");
            return;
        }
        ToastUtil.showToast("选择:" + mSelectAddress);
        addAddress().subscribe(new DialogObserver<Boolean>(this) {
            @Override
            public void onNextTo(Boolean aBoolean) {
                if(aBoolean){
//                    if(mType==TYPE_ADD){
                    ToastUtil.showToast("绑定成功");
//                    }else if(mType==TYPE_UPDATE){
//                        ToastUtil.showToast("保存成功");
//                    }
                    finish();
                }
            }
        });
    }
    public void onClickCollapse(View v) {
        mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
    }
    public void onSearchKeyword(View v) {
        mKeyWords = et_keyword.getText().toString();
        doSearchQuery(mKeyWords);
        SoftInputUtil.INSTANCE.hideSoftInput(this, v);
    }

    public static String sHA1(Context context){
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static final String ADD_UPDATE_ADDR="address/edit"; //删除地址

    public Observable<Boolean> addAddress(/**/) {
        AddressCommitBean addressCommitBean = new AddressCommitBean();
        if (mAddressInfoBean != null) {
            addressCommitBean.copy(mAddressInfoBean);
        }
        Map<String,Object> parm= MapBuilder.factory()
                .put("is_default",1)
                .put("real_name",mSelectTitle)
                .put("address[province]",mSelectLat)
                .put("address[city]",mSelectLng)
                .put("address[district]",mSelectTitle)
                .put("address[city_id]",addressCommitBean.getCityId())
                .put("phone","13888888888")
                .put("post_code","")
                .put("id",addressCommitBean.getId())
                .put("detail",mSelectAddress)
                .build();
        return RequestFactory.getRequestManager().commit(ADD_UPDATE_ADDR,parm,false);
    }
    public static final String DEFAULT_ADDRESS="address/default"; //获取默认地址
    /*获取默认地址*/
    public static void getDefaultAddress(BaseHttpCallBack baseHttpCallBack){
        HttpClient.getInstance().get(DEFAULT_ADDRESS,DEFAULT_ADDRESS)
                .execute(baseHttpCallBack);
    }
}